import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import LoginView from '../views/LoginView.vue'

// 公共路由 - 不需要登录即可访问
const publicRoutes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: {
      title: '登录',
      guestLayout: true, // 标记为公共页面
    },
  },
  {
    path: '/',
    redirect: '/login', // 根路径重定向到登录页
  },
]

// 需要登录才能访问的路由 - 三角色分区（懒加载）
const authRoutes = [
  // 学生端
  {
    path: '/student/leave/list',
    name: 'studentLeaveList',
    component: () => import('../views/student/LeaveList.vue'),
    meta: { title: '我的请假', requiresAuth: true, roles: ['student'] },
  },
  {
    path: '/student/leave/new',
    name: 'studentLeaveNew',
    component: () => import('../views/student/LeaveNew.vue'),
    meta: { title: '新建请假', requiresAuth: true, roles: ['student'] },
  },
  {
    path: '/student/leave/:id',
    name: 'studentLeaveDetail',
    component: () => import('../views/student/LeaveDetail.vue'),
    meta: { title: '请假详情', requiresAuth: true, roles: ['student', 'admin', 'teacher'] },
  },

  // 老师端
  {
    path: '/teacher/approvals',
    name: 'teacherApprovals',
    component: () => import('../views/teacher/ApprovalsList.vue'),
    meta: { title: '待办审批', requiresAuth: true, roles: ['teacher'] },
  },
  {
    path: '/teacher/approvals/:id',
    name: 'teacherApprovalDetail',
    component: () => import('../views/teacher/ApprovalDetail.vue'),
    meta: { title: '审批详情', requiresAuth: true, roles: ['teacher'] },
  },

  // 管理员
  {
    path: '/admin/leave/list',
    name: 'adminLeaveList',
    component: () => import('../views/admin/LeaveManageList.vue'),
    meta: { title: '请假管理', requiresAuth: true, roles: ['admin'] },
  },
  {
    path: '/admin/leave/stats',
    name: 'adminLeaveStats',
    redirect: '/admin/leave/list',
    meta: { title: '统计概览', requiresAuth: true, roles: ['admin'] },
  },
]

// 404 页面路由 - 必须放在最后，捕获所有未匹配的路由
const notFoundRoute = {
  path: '/:pathMatch(.*)*',
  name: 'notFound',
  component: () => import('../views/NotFoundView.vue'),
  meta: {
    title: '页面不存在',
    guestLayout: true, // 404 页面作为公共页面
  },
}

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...publicRoutes, ...authRoutes, notFoundRoute],
  // 滚动行为
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  },
})

// 路由守卫（基于 Pinia）
router.beforeEach((to, from, next) => {
  const appTitle = '学生请假系统'
  document.title = to.meta.title ? `${to.meta.title} - ${appTitle}` : appTitle

  const auth = useAuthStore()
  // 确保刷新后恢复一次
  if (!auth.token) auth.restore()

  const isPublicPage = to.matched.some((record) => record.meta.guestLayout === true)

  if (isPublicPage) {
    if (auth.isAuthenticated && to.name === 'login') {
      const redirect = to.query.redirect
      if (redirect && typeof redirect === 'string') return next(redirect)
      // 已登录访问登录页时，按角色默认分流
      if (auth.isStudent) return next('/student/leave/list')
      if (auth.isTeacher) return next('/teacher/approvals')
      if (auth.isAdmin) return next('/admin/leave/list')
      return next('/')
    }
    return next()
  }

  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth !== false)
  if (requiresAuth && !auth.isAuthenticated) {
    return next({ path: '/login', query: { redirect: to.fullPath } })
  }

  const allowedRoles = to.matched.flatMap((r) => (Array.isArray(r.meta.roles) ? r.meta.roles : []))
  if (allowedRoles.length > 0 && auth.role && !allowedRoles.includes(auth.role)) {
    if (auth.isStudent) return next('/student/leave/list')
    if (auth.isTeacher) return next('/teacher/approvals')
    if (auth.isAdmin) return next('/admin/leave/list')
  }

  next()
})

export default router
